package cn.enjoy.redisson.controller;

import cn.enjoy.redisson.entity.SomeObject;
import lombok.AllArgsConstructor;
import org.redisson.api.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.concurrent.TimeUnit;

/**
 * 分布式集合
 *
 * @author K
 * @date 2024-04-16 16:28
 */
@RestController
@AllArgsConstructor
@RequestMapping("collection")
public class CollectionController {

    private RedissonClient redisson;


    /**
     * 有序集（SortedSet）
     */
    @GetMapping("SortedSet")
    public void SortedSet() {

        RSortedSet<Integer> set = redisson.getSortedSet("SortedSet");
        set.trySetComparator(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        }); // 配置元素比较器
        set.add(3);
        set.add(1);
        set.add(2);

        set.removeAsync(0);
        set.addAsync(5);

        System.out.println();
    }

    /**
     * 计分排序集（ScoredSortedSet）
     */
    @GetMapping("ScoredSortedSet")
    public void ScoredSortedSet() {
        RScoredSortedSet<SomeObject> set = redisson.getScoredSortedSet("ScoredSortedSet");
        set.add(0.13, new SomeObject("a", 0));
        set.addAsync(0.251, new SomeObject("c", 1));
        set.add(0.302, new SomeObject("g", 1));

//        set.pollFirst();
//        set.pollLast();

        int index = set.rank(new SomeObject("g", 1)); // 获取元素在集合中的位置
//        int index2 = set.rank(new SomeObject("g", 0)); // 获取元素在集合中的位置
        Double score = set.getScore(new SomeObject("g", 1)); // 获取元素的评分

        System.out.println();
    }

    /**
     * 延迟队列（Delayed Queue）
     */
    @GetMapping("DelayedQueue")
    public void DelayedQueue() {
        RQueue<String> distinationQueue = redisson.getQueue("DelayedQueue");
        RDelayedQueue<String> delayedQueue = redisson.getDelayedQueue(distinationQueue);
        // 10秒钟以后将消息发送到指定队列
        delayedQueue.offer("msg1", 5, TimeUnit.SECONDS);
        // 一分钟以后将消息发送到指定队列
//        delayedQueue.offer("msg2", 1, TimeUnit.MINUTES);
        delayedQueue.destroy();
        System.out.println();
    }

    @GetMapping("DelayedQueuePoll")
    public void DelayedQueuePoll() {
        RQueue<String> distinationQueue = redisson.getQueue("DelayedQueue");
        RDelayedQueue<String> delayedQueue = redisson.getDelayedQueue(distinationQueue);
        String str = delayedQueue.poll();

        System.out.println();
    }

}
